package com.zb.springevent.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 线程池
 */
@EnableAsync
@Configuration
public class AsyncThreadPoolConfig implements AsyncConfigurer {

    @Override
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        //获取到cpu内核数
        int cpuNum = Runtime.getRuntime().availableProcessors();
        //核心线程数
        executor.setCorePoolSize(cpuNum);
        //最大线程数
        executor.setMaxPoolSize(cpuNum * 2);
        //队列大小
        executor.setQueueCapacity(200);
        //线程最大空闲时间
        executor.setKeepAliveSeconds(300);
        executor.setThreadNamePrefix("Thread-Pool-");
        // 设置任务丢弃后的处理策略,当poolSize已达到maxPoolSize，如何处理新任务（是拒绝还是交由其它线程处理）,CallerRunsPolicy：不在新线程中执行任务，而是由调用者所在的线程来执
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.initialize();
        return executor;
    }
}
